<template>
	<div v-loading="loading">
		<h2 class="bottom15">用户管理</h2>
		<div class="body_content">
			<div class="content_header_menus">
				<el-button type="primary" @click="addUser">添加用户</el-button>
			</div>
			<el-table ref="tableRef" :data="tableData" style="width: 100%" :max-height="maxHeight" row-key="_id" border
				default-expand-all>
				<el-table-column prop="userName" label="用户名" />
				<el-table-column prop="maxDeviceNum" label="最大控数" />
				<el-table-column prop="isDeviceNum" label="已用控数" />
				<el-table-column label="剩余控数">
					<template #default="scope">
						{{ scope.row.maxDeviceNum - scope.row.isDeviceNum }}
					</template>
				</el-table-column>
				<el-table-column prop="deviceNum" label="设备占控" />
				<el-table-column label="下级占控">
					<template #default="scope">
						{{ scope.row.isDeviceNum - scope.row.deviceNum }}
					</template>
				</el-table-column>
				<el-table-column prop="beiZhu" label="备注" />
				<el-table-column prop="createTime" label="创建时间" />
				<el-table-column label="操作">
					<template #default="scope">
						<el-button size="small" type="warning" @click="editUserFunc(scope.$index, scope.row)"
							:disabled="scope.row.userName == useUser.userInfo.userName ? true : false">
							编辑
						</el-button>
						<el-button size="small" type="warning" @click="editDeviceNumFunc(scope.$index, scope.row)"
							:disabled="scope.row.userName == useUser.userInfo.userName ? true : false">
							修改控数
						</el-button>
						<el-button size="small" type="danger" @click="delUserFunc(scope.$index, scope.row)"
							:disabled="scope.row.userName == useUser.userInfo.userName ? true : false">
							删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
	</div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { allUser, delUser, userGetUserDeviceNumApi, userUpdateMaxDeviceNumApi } from '@/api/user';
import addUserDialog from './components/addUserDialog.vue';
import editUserDialog from './components/editUserDialog.vue';
import { addDialog } from '@/components/yDialog/index.js';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useTableHeight } from '@/hooks/useTableHeight';
import { useUserStore } from '@/store/modules/user.js';

const { tableRef, maxHeight } = useTableHeight();
let tableData = reactive([]);
let loading = ref(false);
const useUser = useUserStore();
console.log(useUser.userInfo);
const addUser = async () => {
	addDialog({
		title: '添加用户',
		width: '800px',
		props: {
			id: 0
		},
		component: addUserDialog,
		callBack: async (data) => {
			await getAllUser();
		},
	});
};

const editDeviceNumFunc = async (index, row) => {
	const res = await userGetUserDeviceNumApi({ userName: row.userName, _id: row._id, parent: row.parent })
	console.log(res)
	console.log('最小分配控数：', res.data.isDeviceNum, '可分配控数：', res.data.isParentMaxDeviceNum - res.data.isParentDeviceNum + row.maxDeviceNum)
	ElMessageBox.prompt(`更改代理[${row.userName}]占用控数，注意：最小分配控数：${res.data.isDeviceNum},可分配控数:${res.data.isParentMaxDeviceNum - res.data.isParentDeviceNum + row.maxDeviceNum}`, '注意', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		inputValue:row.maxDeviceNum,
		inputPattern: /^[0-9]*[1-9][0-9]*$/,
		inputErrorMessage: '请输入正整数',
	}).then(async({ value }) => {
		if(Number(value) < res.data.isDeviceNum){
			return ElMessage({
				type: 'error',
				message: '最大设备数不能小于已分配设备数',
			});
		}
		if(Number(value) > res.data.isParentMaxDeviceNum - res.data.isParentDeviceNum + row.maxDeviceNum){
			return ElMessage({
				type: 'error',
				message: '最大设备数不能大于可分配控数',
			});
		}
		const result = await userUpdateMaxDeviceNumApi({userName:row.userName, parent:row.parent, _id:row._id, maxDeviceNum:value})
		console.log('res',result)
	})
};

const editUserFunc = async (index, row) => {
	addDialog({
		title: '编辑用户',
		width: '800px',
		props: {
			id: row._id,
			row: row
		},
		component: editUserDialog,
		callBack: async (data) => {
			await getAllUser();
		}
	})
}

const delUserFunc = async (index, row) => {
	ElMessageBox.confirm('确认删除用户？', '提醒', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		const res = await delUser({ _id: row._id });
		await getAllUser();
		ElMessage({
			message: res.msg,
			type: res.code == 0 ? 'success' : 'error',
		});
	});
};

const getAllUser = async () => {
	loading.value = true;
	const res = await allUser();
	tableData.length = 0;
	tableData.push(...transformToTree(res.data));
	ElMessage.success('加载成功');
	loading.value = false;
};

onMounted(async () => {
	await getAllUser();
});

function transformToTree(data) {
	const map = {};
	const tree = [];

	// 将每个节点按 _id 存入 map 中，并初始化 children 为一个空数组
	data.forEach((item) => {
		map[item._id] = { ...item, children: [] };
	});

	// 构建树形结构
	data.forEach((item) => {
		if (item.parent === '-1') {
			// 如果没有 parent，说明是根节点，直接放到 tree 中
			tree.push(map[item._id]);
		} else {
			// 如果有 parent，则将当前节点放到父节点的 children 数组中
			if (map[item.parent]) {
				map[item.parent].children.push(map[item._id]);
			}
		}
	});

	// 递归去掉没有子节点的 children 属性
	function removeEmptyChildren(node) {
		if (node.children && node.children.length === 0) {
			delete node.children; // 如果没有子节点，则删除 children 属性
		} else if (node.children) {
			// 否则递归处理子节点
			node.children.forEach(removeEmptyChildren);
		}
	}

	// 遍历树并移除没有子节点的 children
	tree.forEach(removeEmptyChildren);

	return tree;
}
</script>

<style lang="scss" scoped></style>
